const { maindb } = require('../utils/db');
const mongoose = require('mongoose');

const FriendSchema = new mongoose.Schema({
    user: { type: String, index: true, required: true },  // 用户id
    toUser: { type: String, index: true, required: true }, // 好友id
    lastMessage: { type: Object, default: '' }, // 最后一条消息
    isEnd: { type: Boolean, default: false }, // 是否结束, 客服用
    createTime: { type: Date, default: Date.now }, // 创建时间
    updateTime: { type: Date, default: Date.now } // 更新时间
});

const Friend = maindb.model('Friend', FriendSchema);

// 创建好友,并更新最后一条消息，没有则创建
const createFriend = async (friend) => {
    console.log('friend', friend)
    try {
        const friendInfo = await Friend.findOne({ user: friend.user, toUser: friend.toUser });
        if (friendInfo) {
            friend.updateTime = Date.now();
            const result = await Friend.updateOne({ user: friend.user, toUser: friend.toUser }, { $set: friend });
            return Promise.resolve({
                type: "update",
                result
            });
        } else {
            const result = await Friend.create(friend);
            return Promise.resolve({
                type: "create",
                result
            });
        }
    } catch (error) {
        return Promise.reject(error);
    }
}

// 获取好友列表
const getFriendList = async (user, pageData = null) => {
    if (pageData) {
        const { page = 1, limit = 10 } = pageData;
        const skip = (page - 1) * limit;
        const friendList = await Friend.find({ user: user }, { __v: 0 }).skip(skip).limit(limit).sort({ updateTime: -1 });
        const total = await Friend.countDocuments({ user: user });
        return {
            friendList,
            total,
            totalPage: Math.ceil(total / limit)
        };
    } else {
        const friendList = await Friend.find({ user: user }, { __v: 0 }).sort({ updateTime: -1 });
        return friendList;
    }
}

// IM管理端用-沟通列表
const getChatList = async (params) => {
    const { user, page = 1, pageSize = 10 } = params;
    const skip = (Number(page) - 1) * Number(pageSize);
    const friendList = await Friend.find({ user: user }, { __v: 0 }).skip(skip).limit(Number(pageSize)).sort({ updateTime: -1 });
    return friendList;
}

module.exports = {
    Friend,
    createFriend,
    getFriendList,
    getChatList,
}